package com.jiayuge.config;

import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.annotation.web.configurers.ExpressionUrlAuthorizationConfigurer;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;

/**
 * 功能: Security配置  --层
 * <p>Security配置  --层</p >
 * <ul>
 * <li>数据库: 增 删 改 查 </li>
 * <li>{@link SecurityConfig} connect to {@link SecurityConfig}</li>
 * </ul>
 *
 * @Program: SpringSecurity
 * @Date: 2021-10-13 11:08
 * @Version 1.0
 * @Author Jiayu.Yang
 */
@EnableWebSecurity //开启Security
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    //配置页面访问权限
    @Override
    protected void configure(HttpSecurity http) throws Exception {
       //首页所有人可以访问，功能只对应有权限的人才能访问
        http.authorizeRequests().antMatchers("/").permitAll()
                .antMatchers("/level1/**").hasRole("vip1")
                .antMatchers("/level2/**").hasRole("vip2")
                .antMatchers("/level3/**").hasRole("vip3");

        //没有权限跳到登录页面,需要开启登录的页面
        //http.formLogin();
        //定制登录跳转页面
        http.formLogin().loginPage("/login");

        //开启登录注销，默认跳到登录页面，可以指定跳转位置
        http.logout().logoutSuccessUrl("/logout");

        //开启记住我功能 cookie的实现
        http.rememberMe();
    }

    //权限认证
    //密码编码:passwordEncoder
    //speing security5.0+ 密码要加密
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth
//                .jdbcAuthentication()//通过数据库权限认证
//                    .dataSource(dataSource) //传入数据源
//                    .withDefaultSchema()

                .inMemoryAuthentication()//通过缓存权限认证
                    .passwordEncoder(new BCryptPasswordEncoder())
                    .withUser("jiayuge").password(new BCryptPasswordEncoder().encode("123456")).roles("vip3","vip2")
                    .and()//拼接下一个用户
                    .withUser("root").password(new BCryptPasswordEncoder().encode("root")).roles("vip1","vip2","vip3");
    }

}
